/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 公差填写 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
		units: 'mm'
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
	}
	
	var jtg_special_hole = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole"})
	if (/yes/ig.test(jtg_special_hole)) {
		var stepList = GEN.getStepList({job:job})
		// step过滤
		stepList = stepList.filter(function(step){
			var regexp = new RegExp(par.step,"ig")
			return regexp.test(step)
		})

		if (stepList.length == 0 && par.step2) {
			stepList = GEN.getStepList({job:job}).filter(function (v) {
				var tmpreg = new RegExp(par.step2, "ig");
				return tmpreg.test(v);
			})
		}


		if(stepList.length == 0) { throw "未发现step:"+par.step_filter }

		// 公差信息
		var jtg_special_tolerance_hole_diameter_final = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_tolerance_hole_diameter_final"})
		var jtg_pecial_tolerance_hole_diameter_drill = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_pecial_tolerance_hole_diameter_drill"})
		var jtg_special_hole_diameter_tolerance = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_diameter_tolerance"})
		var jtg_special_hole_final1 = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_final1"})
		var jtg_special_hole_drl1 = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_drl1"})
		var jtg_special_hole_diameter_tolerance1 = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_diameter_tolerance1"})
		var jtg_special_hole_final2 = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_final2"})
		var jtg_special_hole_drl2 = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_drl2"})
		var jtg_special_hole_diameter_tolerance2 = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_special_hole_diameter_tolerance2"})



		
		var tolerance = [
			{
				final:jtg_special_tolerance_hole_diameter_final,
				tolerance: jtg_special_hole_diameter_tolerance,
				drl:jtg_pecial_tolerance_hole_diameter_drill
			},
			{
				final:jtg_special_hole_final1,
				tolerance: jtg_special_hole_diameter_tolerance1,
				drl:jtg_special_hole_drl1
			},
			{
				final:jtg_special_hole_final2,
				tolerance: jtg_special_hole_diameter_tolerance2,
				drl:jtg_special_hole_drl2
			}
		]
		tolerance.forEach(function(item) {
			if(item.final) {
				item.final = parseFloat(item.final)*1000
				item.drl = parseFloat(item.drl)*1000
				var tol = getTol(item.tolerance)
				item.max_tol = tol.max_tol;
				item.min_tol = tol.min_tol;
			}
		})
		var drill_layer = "drl"
		stepList.forEach(function(step){
			GEN.openStep({job:job, name:step})
			GEN.clearLayers();  //清除层显示
			GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
			GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
			GEN.units({ type: par.units });  //单位初始化
			GEN.zoomHome();  //窗口显示回到原始位置
			
			setTool({
				job:job, 
				step:step,
				layer:drill_layer,
				units: par.units,
				callback: function (toolinfo) {
					for (var key in toolinfo) {
						var info = toolinfo[key]
						info.finish_size = Number(info.finish_size)
						tolerance.forEach(function(item){
							if(Math.abs(info.finish_size - item.final) <= 2) {
								info.min_tol = item.min_tol
								info.max_tol = item.max_tol
							}
						})
						
					}
				}
			})
		})
	}

	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}



function setTool(props) {
	var units = props.units
	GEN.units({type:"mm"})
	var job = props.job;
	var step = props.step;
	var layer = props.layer;
	var tool_info = GEN.getTool({job:job, step: step , layer:layer, units:"mm"})

	// 操作tool_info
	props.callback(tool_info)

	GEN.COM("tools_show,layer="+layer)
	GEN.COM("tools_tab_reset")
	var typehash = {
		non_plated:"nplate",
		plated:"plate",
		via:"via",
		laser:"via"
	}
	Object.keys(tool_info).forEach(function(key){
		var item = tool_info[key]
		if (item.shape == "hole") {
			GEN.COM("tools_tab_add,num="+key
			+",shape="+item.shape+",type="+typehash[item.type]+",min_tol="+item.min_tol+
			",max_tol="+item.max_tol+",bit=,finish_size="+item.finish_size+
			",drill_size="+item.drill_size+",combined=yes,orig_size=0")
		} else if (item.shape == "slot") {
			GEN.COM("tools_tab_add,num="+key+",shape=slot,type="+typehash[item.type]+",min_tol="+item.min_tol+",max_tol="+item.max_tol+",finish_size="+item.finish_size+
			",bit=,drill_size="+item.drill_size+",slot_len="+item.slot_len)
		}
	
	})
	GEN.COM("tools_set,layer="+layer+",slots=by_length")

	GEN.units({type:units})
}

function getTol(tol) {
	if(/~/.test(tol)) {
	   var tmp = tol.split("~")
	   return {
			min_tol: tmp[0] * 1000,
			max_tol: tmp[1] * 1000
	   }
	}
	if(/±/.test(tol)) {
		var tmp = tol.slice(1)
		return {
			min_tol: tmp * 1000,
			max_tol: tmp * 1000
	   	}
	}

	return {
		min_tol: 0,
		max_tol: 0
	}
}